package zd.cornermemory.ui;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import greendao.CjDao;
import zd.cornermemory.R;
import zd.cornermemory.adapter.AoCjAdapter;
import zd.cornermemory.db.Cj;
import zd.cornermemory.utils.Statistics;

import static zd.cornermemory.utils.Statistics.timeToString;

public class AoDetailActivity extends BaseActivity {
    private CjDao    cjDao;
    private String      titleStr;
    private TextView zpj;
    private TextView min;
    private TextView max;
    private TextView position_text;
    private ListView listview;
    private List<Cj> cjs;
    private Cj minCj,maxCj;
    private AoCjAdapter mAdapter;
    private String avgStr;
    private RelativeLayout zpj_layout;
    private LinearLayout share_layout;
    private View zpj_line;
    private Toast copyToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ao_detail);
        findViews();
        initData();
        setEvent();
        setBackImage();
    }

    private void setEvent() {
    }

    private void initData() {
        titleStr = getIntent().getExtras().getString("titleStr");
        position_text.setText(titleStr);
        cjs = (List<Cj>) getIntent().getExtras().getSerializable("cj");
        if (cjs == null||cjs.size()==0) {
            cjs = new ArrayList<>();
        }
        mAdapter = new AoCjAdapter(mContext, cjs);
        listview.setAdapter(mAdapter);

        zpj_layout.setVisibility(View.VISIBLE);
        zpj_line.setVisibility(View.VISIBLE);
        setDevition(cjs);
        copyToast = Toast.makeText(mContext,getString(R.string.copied), Toast.LENGTH_SHORT);
        share_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", getCjStr());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                copyToast.show();
            }
        });
    }

    private String getCjStr(){
        StringBuffer buffer = new StringBuffer();
        for (int position = 0; position < cjs.size(); position++) {
            Cj cj = cjs.get(position);
            String code = cj.getCode();
            String time = Statistics.timeToString(cj.getSingTime().intValue());
            switch (cj.getStatus()) {
                case 0:
                    break;
                case 1://+2
                    time += "+";
                    break;
                case 2:
                    time = "DNF" + " (" + time + ")";
                    break;

            }
            time = position + 1 + ".  " + time;
            time+=" ";
            time += code;
            time += "\n";
            buffer.append(time);
        }
        return buffer.toString();
    }


    private void findViews() {
        zpj = findViewById(R.id.zpj);
        min = findViewById(R.id.min);
        max = findViewById(R.id.max);
        share_layout = findViewById(R.id.share_layout);
        zpj_layout = findViewById(R.id.zpj_layout);
        zpj_line = findViewById(R.id.zpj_line);
        position_text = findViewById(R.id.position_text);
        listview = findViewById(R.id.listview);
    }

    private void setDevition(List<Cj> cjList) {
        List<Cj> ao = new ArrayList<>();
        Cj minCj = null;
        Cj maxCj = null;
        int dnfCount = 0;
        for (Cj cj : cjList) {
            if (cj.getStatus() != 2) {
                ao.add(cj);
            }else{
                dnfCount++;
                maxCj = cj;
            }

        }

        if (dnfCount >= 1) {
            zpj_layout.setVisibility(View.GONE);
            zpj_line.setVisibility(View.GONE);
            max.setText("DNF");
            if(ao.size()>0){
                minCj = Collections.min(ao);
                min.setText(Statistics.timeToString(minCj.getSingTime().intValue()));
            }else {
                min.setText("DNF");
            }
            return;
        }

        if (maxCj != null) {
            minCj = Collections.min(ao);
            ao.remove(minCj);
        }else{
            minCj = Collections.min(cjList);
            maxCj = Collections.max(cjList);
            if (cjList.size() != 3) {
                ao.remove(minCj);
                ao.remove(maxCj);
            }

        }

        long avg = 0;
        for (Cj cj : ao) {
                avg += cj.getSingTime();
        }
        double a = avg/ao.size();
        avg = Math.round(a);
        String avgStr = timeToString((int) avg);

        min.setText(Statistics.timeToString(minCj.getSingTime().intValue()));
        String maxStr = "";
        if (maxCj.getStatus() == 2) {
            maxStr = "DNF";
        }else{
            maxStr = Statistics.timeToString(maxCj.getSingTime().intValue());
        }
        max.setText(maxStr);

        long sum = 0;
        for (Cj c : ao) {
            long time = c.getSingTime();
            sum += (time-avg)*(time-avg);
        }
        double s = sum/(ao.size()-1);
        double standardDevition = Math.sqrt(s)/1000;
        DecimalFormat format = new DecimalFormat("######0.00");

        zpj.setText(avgStr+"(σ = "+format.format(standardDevition)+")");

    }


}
